package org.aeon.client.view.components.listColumn;

import org.aeon.utils.NewScrollBarUI;

import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * @author: MissingAeon
 * @date: 2024/2/22 16:27
 * @description:
 */
public class ColumnScrollPanel extends JScrollPane {
    private final static GridBagConstraints gbc;

    static {
        // 创建 GridBagConstraints 对象以控制组件布局
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        // 使组件在垂直方向上相对于上一个组件定位
        gbc.gridy = GridBagConstraints.RELATIVE;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        // 设置组件之间的间距
        gbc.insets = new Insets(0, 3, 0, 2);
    }

    private final JPanel panel = new JPanel(new GridBagLayout());

    public ColumnScrollPanel(Dimension preferredSize) {
        this.getVerticalScrollBar().setUI(new NewScrollBarUI());
        Border border = BorderFactory.createMatteBorder(1, 0, 1, 0,
                new Color(0xA0CECECE, true));
        this.setBorder(border);

        this.getVerticalScrollBar().setUnitIncrement(10);

        final Box box = Box.createVerticalBox();
        box.add(panel);
        box.add(Box.createVerticalGlue());
        this.setViewportView(box);

        // 设置 JScrollPane 的大小
        this.setPreferredSize(preferredSize);
        this.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                ColumnScrollPanel.this.requestFocus();
            }
        });
    }

    /**
     * 将容器清理
     */
    public void clean() {
        panel.removeAll();
        panel.revalidate();
        panel.repaint();
    }

    /**
     * 添加一项到顶部
     *
     * @param component
     */
    public void addItem(Component component) {
        panel.add(component, gbc);
        panel.setMaximumSize(new Dimension(Integer.MAX_VALUE, panel.getMinimumSize().height + 500));
        panel.revalidate();
        panel.repaint();
    }


    /**
     * 删除一项
     *
     * @param component
     */
    public void removeItem(Component component) {
        panel.remove(component);
        panel.setMaximumSize(new Dimension(Integer.MAX_VALUE, panel.getMinimumSize().height + 500));
        panel.revalidate();
        panel.repaint();
    }
// TODO 排序

}
